import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shop/common/common.dart';
import 'package:shop/page/good_detail_page.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  final List _data = [];
  final List<String> _imgs = [
    'https://icweiliimg1.pstatp.com/weili/bl/314677504937033780.jpg',
    'https://icweiliimg1.pstatp.com/weili/bl/466330025636659337.jpg',
    'https://p0.ssl.qhimgs1.com/sdr/400__/t010df96662f0e6d254.jpg',
    'http://img1.mydrivers.com/img/20200127/s_620b3be57620491eab1d001a54000297.jpg',
    'http://img10.360buyimg.com/n12/jfs/t424/150/538882248/141332/76395aa1/54224df3N0e21131e.jpg!q70.jpg',
    'http://img1.gtimg.com/fashion/pics/hv1/107/151/2030/132039362.jpg',
    'http://m.360buyimg.com/n12/jfs/t2101/354/150042360/59206/8120d43d/55f0f72cN0023aa71.jpg!q70.jpg',
    'http://img.zcool.cn/community/018f925a1e5aa8a80120908d912b8c.jpg@1280w_1l_2o_100sh.jpg',
    'https://p0.ssl.qhimgs1.com/sdr/400__/t013f67ce23a606411a.jpg',
    'https://icweiliimg1.pstatp.com/weili/bl/490364430701035882.jpg',
    'https://p1.ssl.qhimgs1.com/sdr/400__/t01b54e601787ce49d7.jpg',
    'https://p3.ssl.qhimgs1.com/sdr/400__/t01e415e16aa76107fd.png',
    'http://img.china.alibaba.com/img/ibank/2014/343/481/1454184343_648399795.jpg',
    'https://icweiliimg1.pstatp.com/weili/bl/235420291580559385.jpg',
    'https://img.alicdn.com/imgextra/i4/1102525876/O1CN01sKDSP31tHG4B7NElh_!!1102525876.jpg',
    'https://gd1.alicdn.com/imgextra/i1/1037052343/O1CN01FcchUc1TB8mQ9O5ik_!!1037052343.jpg',
    'https://gd3.alicdn.com/imgextra/i3/2206442682609/O1CN01g1f1Zr1V8y4Nh6SE0_!!2206442682609.jpg',
    'https://icweiliimg1.pstatp.com/weili/bl/481293305153060905.jpg',
    'https://gd2.alicdn.com/imgextra/i2/1896264785/O1CN01G64gNw1lDZyJV9FlR_!!1896264785.jpg',
    'https://p2.ssl.qhimgs1.com/sdr/400__/t0198cd55ee05a31388.jpg'
  ];
  final List<String> _title = [
    '柏文熊泰迪熊毛绒玩具熊抱抱熊公仔大熊猫娃娃毛衣小熊生日礼物女',
    '恒源祥本命年红色毛衣男士冬装加厚圆领纯羊毛衫中老年爸爸针织衫',
    '西装毛呢外套女秋冬新款小个子宽松呢大衣黑色',
    '欧美复古休闲潮牌ins夏季短袖T恤男女宽松百搭原宿半袖上衣情侣装',
    '汤普葛罗秋冬新款时尚尖头短筒靴纯色西部牛仔靴粗跟靴子女',
    '雅诗兰黛口红倾慕哑光唇膏333显白持久557保湿',
    'CHANEL香奈儿炫亮魅力唇膏丝绒系列哑光持妆口红58',
    'MAC炫彩唇膏口红',
    '玩具小鸭子',
    '玩具火车',
    '玩具小熊',
    '英国jELLYCAT正版小熊可爱毛绒玩具送礼儿童玩偶礼物',
    '玩具小车',
    '毛绒小狗',
    '拖鞋',
    '文具',
    '男女小众重工饰品亚文化高级感设计 顺丰到付不退不换',
    '老式复古电熨斗',
    '耳钉耳环',
    '电器微波炉',
  ];
  @override
  void initState() {
    super.initState();
    _getData();
  }

  void _getData() async {
    final res = await Dio().get('https://api.apiopen.top/api/getImages?type=phone&page=0&size=20');
    if (res.statusCode == 200) {
      final _list = res.data["result"]["list"];
      print("-----$_list");
      _data.addAll(_list);
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: AppColor.mainColor,
        title: Text("首页"),
      ),
      body: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisSpacing: 0,
          crossAxisSpacing: 0,
        ),
        itemBuilder: (context, index) {
          final model = _data[index];
          final _str = '二手-${index < _title.length ? _title[index] : model['title']}';
          return GestureDetector(
            onTap: () {
              Navigator.push(
                context,
                CupertinoPageRoute(
                  builder: (context) {
                    return GoodDetailPage(
                      model: model,
                      title: _str,
                      img: _imgs[index],
                    );
                  },
                ),
              );
            },
            child: Card(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
              clipBehavior: Clip.antiAlias,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Stack(
                      fit: StackFit.expand,
                      children: [
                        CachedNetworkImage(
                          imageUrl: _imgs[index],
                          fit: BoxFit.cover,
                        ),
                        Positioned(
                          top: 6,
                          right: 6,
                          child: _StarView(),
                        )
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8, top: 6),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          _str,
                          style: AppFont.textStyle(16, color: Colors.black),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 8),
                        Row(
                          children: [
                            Text(
                              "\$${model['id'] / 1000}",
                              style: AppFont.textStyle(
                                18,
                                fontWeight: FontWeight.bold,
                                color: Colors.redAccent,
                              ),
                              maxLines: 2,
                            ),
                            Spacer(),
                            const Icon(
                              Icons.shopping_cart_sharp,
                              color: Colors.redAccent,
                              size: 18,
                            )
                          ],
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          );
        },
        itemCount: _data.length,
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class _StarView extends StatefulWidget {
  const _StarView({Key? key}) : super(key: key);

  @override
  State<_StarView> createState() => _StarViewState();
}

class _StarViewState extends State<_StarView> {
  bool _started = false;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _started = !_started;
        });
      },
      child: Icon(
        Icons.star,
        size: 18,
        color: _started ? Colors.yellow : Colors.grey,
      ),
    );
  }
}
